<script setup>
import ScSelector from "@/components/scSelector/ScSelector.vue";
import LimitFram from "./LimitFrame.vue";
import { getUserGroupPagerApi } from "@/api/activity";
import { deepClone } from "@/utils";

const props = defineProps({
  limit: {
    type: Object,
    required: true,
  },
});

const ruleData = ref({
  0: "userGroupAllNo",
  1: "userGroupAny",
  2: "userGroupAll",
});

const blackGroupVisible = ref(false),
  form = ref({ exit: 1, groupId: [] }),
  blacklist = ref([]);

const formRef = ref();

const emits = defineEmits(["cancel"]);

const rules = {
  groupId: [{ required: true, message: "请选择客群", trigger: "change" }],
};

// 描述
const ruleText = computed(() => {
  let rule = props.limit.value;
  if (!rule.groupId) return "";
  return `${
    rule.exit == 1 ? "任意匹配" : rule.exit == 2 ? "全匹配" : "不匹配"
  } “${String(rule.groupName)}”`;
});

const getUserGroupPager = async () => {
  const rs = await getUserGroupPagerApi({
    currentPage: 1,
    showCount: -1,
  });
  if (rs.code == 200) {
    blacklist.value = rs.payload.map((item) => {
      return { value: item.id, label: item.name };
    });
  }
};

const getBlackKeys = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      props.limit.value = deepClone(form.value);
      formatLimit();
      blackGroupVisible.value = false;
    }
  });
};

// 生成表达式
const formatLimit = () => {
  // 表达式最终的样子
  // $_user_group.userGroupAll$$_1_2_3 == true

  // props.limit.propertyKey = "userGroup";
  // props.limit.propertyType = 0;
  // props.limit.businessType = "userGroup";
  // let sentencedToEmpty = `$_user_group.${
  //   ruleData.value[form.value.exit]
  // }$$_${form.value.groupId.join("__")} != null &&`; // 表达式判空
  props.limit.keys = [
    {
      businessType: "user_group",
      key: `${ruleData.value[form.value.exit]}$$_${form.value.groupId.join("__")}`,
      obj: form.value.groupId
    },
  ];
  props.limit.expression = `$_user_group.${
    ruleData.value[form.value.exit]
  }$$_${form.value.groupId.join("__")}==true`;
};

const addRule = () => {
  if (formRef.value) formRef.value.resetFields();
  blackGroupVisible.value = true;
};

const editRule = () => {
  form.value = deepClone(props.limit.value);
  blackGroupVisible.value = true;
};

const onClose = () => {
  emits("cancel");
};

const onChangeGroup = (val) => {
  let group = val.selected.map((item) => item.title);
  // blacklist.value.forEach((item) => {
  //   if (val.includes(item.value)) {
  //     group.push(item.label);
  //   }
  // });
  if (group.length) {
    form.value.groupName = group;
  }
};

onMounted(() => {
  // getUserGroupPager();
});

defineExpose({ add: addRule });
</script>
<template>
  <LimitFram title="客群限制" :content="ruleText" @edit="editRule" />
  <Dialog
    v-model="blackGroupVisible"
    title="客群限制"
    :width="500"
    @confirm="getBlackKeys"
    @close="onClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="类型" prop="exit">
        <el-radio-group v-model="form.exit">
          <el-radio :label="1">任意匹配</el-radio>
          <el-radio :label="0">不匹配 </el-radio>
          <el-radio :label="2">全匹配</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="客群" prop="groupId">
        <!-- <el-select-v2
          v-model="form.groupId"
          :options="blacklist"
          filterable
          multiple
          placeholder="请选择客群"
          @change="onChangeGroup"
        /> -->
        <ScSelector
          v-model="form.groupId"
          type="userGroup"
          multiSelect
          @change-selected="onChangeGroup"
        >
          <template #expand-pop="{ data }">
            <div v-if="data" class="detail-container">
              <h3>
                {{ data.info.name }}
              </h3>
              <div class="detail-text_line">
                所属机构：
                {{ data.info.insName }}
              </div>
              <div class="detail-text_line">
                所属分组：
                {{ data.info.groupName || "全部" }}
              </div>
              <div>
                客群用途：
                {{ data.info.remark || "" }}
              </div>
            </div>
          </template>
        </ScSelector>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<style lang="scss" scoped>
.el-select-v2 {
  min-width: 70%;
}

.detail-container {
  .detail-text_line {
    white-space: nowrap;
  }
}
</style>
